package com.martin.ads.vrlib.programs;

import android.content.Context;
import android.opengl.GLES20;

import com.martin.ads.vrlib.utils.ShaderUtils;


/**
 * Created by Ads on 2016/11/19.
 * with Sampler2D and MVPMatrix
 */

public class GLRGBProgram  {

    private int mProgramId;

    private String mVertexShader;
    private String mFragmentShader;
    private int maPositionHandle;
    private int mRgbHandle;
    private int uMVPMatrixHandle;

    public GLRGBProgram(Context context) {
        mVertexShader = ShaderUtils.readAssetsTextFile(context, "filter/vsh/rgb.glsl");
        mFragmentShader= ShaderUtils.readAssetsTextFile(context, "filter/fsh/rgb.glsl");
    }

    public int getProgramId() {
        return mProgramId;
    }

    public void create() {
        mProgramId = ShaderUtils.createProgram(mVertexShader, mFragmentShader);
        if (mProgramId == 0) {
            return;
        }

        maPositionHandle = GLES20.glGetAttribLocation(getProgramId(), "aPosition");
        ShaderUtils.checkGlError("glGetAttribLocation aPosition");
        if (maPositionHandle == -1) {
            throw new RuntimeException("Could not get attrib location for aPosition");
        }
        mRgbHandle = GLES20.glGetUniformLocation(getProgramId(), "aRgb");
        ShaderUtils.checkGlError("glGetUniformLocation aRgb");
        if (mRgbHandle == -1) {
            throw new RuntimeException("Could not get glGetUniformLocation aRgb");
        }
        uMVPMatrixHandle=GLES20.glGetUniformLocation(getProgramId(),"uMVPMatrix");
        ShaderUtils.checkGlError("glGetUniformLocation uMVPMatrix");
    }

    public void use(){
        GLES20.glUseProgram(getProgramId());
        ShaderUtils.checkGlError("glUseProgram");
    }

    public int getPositionHandle() {
        return maPositionHandle;
    }

    public int getRGBHandle() {
        return mRgbHandle;
    }

    public int getMVPMatrixHandle() {
        return uMVPMatrixHandle;
    }

    public void onDestroy(){
        GLES20.glDeleteProgram(mProgramId);
    }
}
